﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Sendz.Validators
{
    public class MustMatchValidator : DataAnnotationsModelValidator<MustMatchAttribute>
    {
        public MustMatchValidator(ModelMetadata metadata, ControllerContext context, MustMatchAttribute attribute) : base(metadata, context, attribute) { }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // Get a reference to the property this validation depends upon
            var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);

            if (field != null)
            {
                // Get the value of the dependent property
                var value = field.GetValue(container, null);

                // Compare the value against the target value, only validate when non-null
                if (value != null && Metadata.Model != null)
                {
                        // Sometimes an array will be used since the ViewModel may capture multiple-item values in an array, so check for that
                        var thisVal = (Metadata.Model.GetType().ToString() == "System.String[]") ? string.Join(string.Empty, ((string[])Metadata.Model)) : (string)Metadata.Model;

                        if (value.ToString().ToLowerInvariant() != thisVal.ToLowerInvariant())
                            // Validation failed - return an error
                            yield return new ModelValidationResult { Message = ErrorMessage };
                }
            }
        }
        // No client-side needed with MVC Roundtrip validation! :)
    }
}
